package com.jxs.android.weixi;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.StartHelper;
import com.jxs.android.weiget.BuAlertDailog;
import com.jxs.android.weiget.LaucherTopBar;
import com.jxs.android.weiget.PopMsg;
import com.jxs.android.weixi.data.NoticeInfo;
import com.telecom.weixi.R;

public class LaucherMain extends MyTabHoster implements OnCheckedChangeListener {
	private TabHost mTabHost;
	private RadioGroup mNaviButtons;
	private Context context;

	private final String MY_WORK_TAB = "my_work_tab";
	private final String MY_INFO_TAB = "my_info_tab";
	private final String SYS_NOTI_TAB = "system_notice_tab";
	private final String SYS_MORE_TAB = "system_more_tab";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.context = this;

		initLaucherTopBar(savedInstanceState, R.layout.bu_laucher_main);
		mNaviButtons = (RadioGroup) findViewById(R.id.navi_buttons);

		mTabHost = getTabHost();

		mTabHost.addTab(getTabSpec(mTabHost, MY_WORK_TAB, LaucherApp.class));
		mTabHost.addTab(getTabSpec(mTabHost, MY_INFO_TAB, LaucherMyInfo.class));
		mTabHost.addTab(getTabSpec(mTabHost, SYS_NOTI_TAB,
				LaucherSystemNotice.class));
		mTabHost.addTab(getTabSpec(mTabHost, SYS_MORE_TAB,
				LaucherSystemMore.class));

		((RadioGroup) findViewById(R.id.navi_buttons))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.my_work_tab)).setChecked(true);

		getLatestNotice(WeixiApplication.getUserInfo().getTicket());
		register();
	}

	@Override
	public void topBarLogic(LaucherTopBar topBar) {
		topBar.hindAllBtn();
		topBar.setTitle(R.string.app_name);
	}

	private TabSpec getTabSpec(TabHost tabHost, String tab, Class<?> clazz) {
		Intent appIntent = new Intent(this, clazz);
		return tabHost.newTabSpec(tab).setIndicator(tab).setContent(appIntent);
	}

	private void getLatestNotice(final String ticket) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String wsdl_url = WeixiApplication.WSDL_URL;// wsdl
				String namespace = WeixiApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "getLatestNotice";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);
				request.addProperty("ticket", ticket);
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope)
							throws IOException, XmlPullParserException {
						SoapObject response = (SoapObject) envelope
								.getResponse();
						paser(response);
					}

					@Override
					public void error(String message, Exception e) {
						Message msg = new Message();
						msg.what = ERROR_MSG;
						msg.obj = message;
						handler.sendMessage(msg);
					}

				});
			}
		}).start();
	}

	private void paser(SoapObject soapObject) {
		String stauts = soapObject.getProperty("status").toString();
		SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
		String message = msgObjec.getProperty("message").toString();
		if ("-2".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
		} else if ("-1".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
			StartHelper.startActivity(Login.class);
			this.finish();
		} else if ("0".equals(stauts)) {
			SoapObject taskBeanObject = (SoapObject) soapObject
					.getProperty("retMsg");
			if (null != taskBeanObject) {
				NoticeInfo noticeListInfo = new NoticeInfo();
				noticeListInfo.setNotice_id(taskBeanObject.getProperty(
						"notice_id").toString());
				noticeListInfo.setNotice_title(taskBeanObject.getProperty(
						"notice_title").toString());
				noticeListInfo.setNotice_date(taskBeanObject.getProperty(
						"notice_date").toString());
				noticeListInfo.setNotice_content(taskBeanObject.getProperty(
						"notice_content").toString());
				Message msg = new Message();
				msg.what = SHOW_ALERT;
				msg.obj = noticeListInfo;
				handler.sendMessage(msg);
			}
		}
	}

	private void show(NoticeInfo info, final Intent intent) {

		BuAlertDailog.builder(context, getString(R.string.title_notice),
				info.getNotice_title(),
				new BuAlertDailog.AlertOkAndCancelListener() {

					@Override
					public void okLogic(Dialog dialog) {
						context.startActivity(intent);
						dialog.cancel();
					}

					@Override
					public String getOkText(Context context) {
						return getString(R.string.prompt_watch);
					}

					@Override
					public String getCancleText(Context context) {
						return getString(R.string.prompt_cancel);
					}

					@Override
					public void cancelLogic(Dialog dialog) {
						dialog.cancel();
					}
				}).show();

	}

	private int SHOW_ALERT = 0x331;
	private int ERROR_MSG = 0x332;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (MemoryUtil.isCurrentActivity(LaucherMain.class)) {
				if (msg.what == SHOW_ALERT) {
					if (null != msg.obj) {
						NoticeInfo info = (NoticeInfo) msg.obj;
						Intent intent = new Intent(context,
								LaucherSystemNoticeDetail.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("noticeInfo", info);
						intent.putExtras(bundle);
						show(info, intent);
					}
				} else if (msg.what == ERROR_MSG) {
					PopMsg.show(context, msg.obj.toString());
				}
			}
		}
	};

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.my_work_tab:
			setTabByTag(MY_WORK_TAB);
			break;
		case R.id.my_info_tab:
			setTabByTag(MY_INFO_TAB);
			break;
		case R.id.system_notice_tab:
			setTabByTag(SYS_NOTI_TAB);
			break;
		case R.id.system_more_tab:
			setTabByTag(SYS_MORE_TAB);
			break;
		default:
		}
	}

	public void hideNiveBtns(boolean isHide) {
		if (isHide) {
			mNaviButtons.setVisibility(View.GONE);
		} else {
			mNaviButtons.setVisibility(View.VISIBLE);
		}
	}

	private void setTabByTag(String tag) {
		mTabHost.setCurrentTabByTag(tag);
	}

	// 监听系统新安装程序的广播
	private void register() {
	}

	private void unRegister() {
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegister();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MenuCloseHolder.processMenuClose(this);
		}
		return false;
	}

	/**
	 * @Des 处理关闭
	 * @param context
	 */

	static public final class MenuCloseHolder {

		public static void processMenuClose(final Activity activity) {
			BuAlertDailog.builder(activity,
					activity.getString(R.string.promp_tip),
					activity.getString(R.string.prompt_exit_quest),
					new BuAlertDailog.AlertOkAndCancelListener() {
						@Override
						public void okLogic(Dialog dialog) {
							dialog.dismiss();
							activity.finish();
						}

						@Override
						public String getOkText(Context context) {
							return context.getString(R.string.prompt_exit);
						}

						@Override
						public String getCancleText(Context context) {
							return context.getString(R.string.prompt_cancel);
						}

						@Override
						public void cancelLogic(Dialog dialog) {
							dialog.dismiss();
						}
					}).show();
		}
	}

}
